﻿using InfoFlash;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace InfoFlashServer
{
    //public class ClientList : List<TcpClient> { }
    public class ClientManagers : List<ClientManager> {}

    public delegate void ClientMessageRecievedHandler(TcpClient tcpClient, MessageData msg);

    public class ClientManager
    {
        public string ComputerName { get; set; }
        public string IPAddressAndPort{ get; set; }

        public event ClientMessageRecievedHandler ClientMessageRecieved;
        public TcpClient ClientSocket;
        string clNo;

        public void OnMessageRecieved(TcpClient tcpClient, MessageData msg)
        {
            if (ClientMessageRecieved != null) this.ClientMessageRecieved(tcpClient, msg);
        } 

        public void StartClient(TcpClient inClientSocket, string clineNo)
        {
            this.ClientSocket = inClientSocket;
            this.clNo = clineNo;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();

        }

        private void doChat()
        {
            int requestCount = 0;

            requestCount = 0;
            bool running = true;
            while ((running))
            {
                try
                {
                    if (ClientSocket.Connected)
                    {
                        requestCount = requestCount + 1;



                        NetworkStream stream = ClientSocket.GetStream();
                        BinaryFormatter bf = new BinaryFormatter();
                        MessageData md = new MessageData();
                        md = (MessageData)bf.Deserialize(stream);
                        Console.WriteLine(" >> " + "From client- " + clNo + md.Message + " ipAddress: " + ClientSocket.Client.RemoteEndPoint.ToString());
                        this.OnMessageRecieved(ClientSocket, md);

        
                        stream.Flush();
                        Console.WriteLine(" >> " + md.Message);
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                    ClientSocket.Close();
                    running = false;
                }
            }
        }
        public static byte[] ToByteArray(object source)
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, source);
                return stream.ToArray();
            }
        }
    } 
}
